package web{
	import flash.display.Shape;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	import morn.core.components.Box;
	import morn.core.components.Component;
	import morn.core.components.Image;
	import morn.core.components.Label;
	import morn.core.components.ScrollBar;
	import morn.core.handlers.Handler;
	import ui.down.WebResultUI;
	/**
	 * 测试进度与结果
	 * @author SXL
	 */
	public class WebResult extends WebResultUI{
		private const STATUS_ING:int=2;
		private const STATUS_WAIT:int=1;
		private const STATUS_RESULT:int=3;
		
		private static const TIME_OUT:int=610;
		private static var _instance:WebResult;
		public static function get instance():WebResult{
            if (!_instance){
                _instance = new WebResult();
            }
            return _instance;
        }
		/**当前测试的网址的下标*/
		private var index:int;
		/**当前网址开始时间*/
		private var sTime:int;
		/**当前要测试的网址列表*/
		private var urls:Array;
		/**当前的时间函数*/
		private var timer:Timer;
		/**当前List的滚动条*/
		private var scrollBar:ScrollBar;
		/**回传给后台的*/
		private var urlInfo:String;
		private var bandInfo:Object;
		public function WebResult(){
			this.timer=new Timer(10);
			this.timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		public function start(urls:Array,urlInfo:String,band:Object):void{
			App.scene.scene=this;
			this.index=0;
			this.mcStatus.frame=2;
			this.urlInfo=urlInfo;
			this.bandInfo=band;
			
			this.urls=[];
			for(var i:int=0;i<urls.length;i++){
				this.urls[i]={
					url:urls[i],
					status:STATUS_WAIT
				}
			}
			this.scrollBar=this.urlList.scrollBar;
			this.urlList.renderHandler=new Handler(this.urlListRender);
			this.urlList.dataSource=this.urls;
			this.addEventListener(TextEvent.LINK,this.onTextLink);
			this.addEventListener(MouseEvent.CLICK,this.onClick);
			this.addEventListener(Event.REMOVED_FROM_STAGE,this.onRemovedFromStage);
			App.timer.doOnce(300,this.callJS);
			this.tfDown.text="提示：如需更专业更准确的宽带测速请下载<a href='event:down'><u><font color='#3577bb'>“中国电信10000管家”</font></u><a>";
			
		}
		
		private function urlListRender(item:Component,index:int):void{
			var data:Object=this.urlList.dataSource[index];
			item.visible=!!data;
			if(!data) return;
			var shape:Shape=item.getChildByName("preShape") as Shape;
			var mcBg:Image=item.getChildByName("mcBg") as Image;
			var tfUrl:Label=item.getChildByName("tfUrl") as Label;
			var tfRes:Label=item.getChildByName("tfRes") as Label;
			var tfTime:Label=item.getChildByName("tfTime") as Label;
			var tfStatus:Label=item.getChildByName("tfStatus") as Label;
			mcBg.visible=false;
			if(!shape){
				shape=new Shape();
				shape.name="preShape";
				item.addChild(shape);
				shape.x=212;
				shape.y=16;
				
			}
			tfUrl.text=data.url;
			switch(data.status){
				case this.STATUS_WAIT:
					shape.visible=false;
					tfTime.visible=false;
					tfStatus.visible=true;
					tfRes.text="等待结果";
					tfStatus.text="还未开始测试";
					tfStatus.color=tfRes.color=0x898989;
					break;
				case this.STATUS_ING:
					tfRes.color=tfStatus.color=0x5d5c5c;
					tfStatus.text="正在测试中...";
					break;
				case this.STATUS_RESULT:
					this.initResult(data,item as Box);
					break;
			}
		}
		private function callJS():void{
            if (!ExternalInterface.available) return
			
			this.urlList.selectedIndex=index;
			var data:Object=this.urls[index];
			data.status=this.STATUS_ING;
			var item:Box=this.urlList.selection as Box;
			var tfRes:Label=item.getChildByName("tfRes") as Label;
			var tfStatus:Label=item.getChildByName("tfStatus") as Label;
			tfRes.color=tfStatus.color=0x5d5c5c;
			tfStatus.text="正在测试中...";
			
            ExternalInterface.addCallback("callAS", callAS);
            ExternalInterface.call("PostOrder", "http://" + this.urls[index].url);
			this.sTime=getTimer();
			this.timer.start();
        }
		/**不停的轮寻JS判断当前的测试状态*/
		private function onTimer(evt:TimerEvent):void{
			if (timer.currentCount>=TIME_OUT||runJs("asverify") == "pass"){
                this.callAS();
            }
		}
		private function callAS():void{
			var xml:XML;
			var data:Object=this.urls[this.index];
            this.timer.reset();
			var useTime:Number = int((getTimer() - this.sTime) * 10) / 10000;
			if (useTime > 10){
                useTime = 10;
            }
			var item:Box=this.urlList.selection as Box;
			data.time=useTime;
			data.status=this.STATUS_RESULT;
			this.initResult(data,item);
			this.index++;
			if(this.index>=7){
				this.scrollBar.value+=this.scrollBar.scrollSize;
			}
			if(this.index>=this.urls.length){
				this.mcStatus.frame=1;
				ExternalInterface.call("returnwebspeed", this.returnJS().toXMLString());
				return;
			}
			App.timer.doOnce(1000,this.callJS);
		}
		private function initResult(data:Object,item:Box):void{
			var color:int;
			var tfRes:Label=item.getChildByName("tfRes") as Label;
			var tfTime:Label=item.getChildByName("tfTime") as Label;
			var shape:Shape=item.getChildByName("preShape") as Shape;
			var tfStatus:Label=item.getChildByName("tfStatus") as Label;
			shape.visible=true;
			tfTime.visible=true;
			tfStatus.visible=false;
			shape.graphics.clear();
			
			tfTime.text = data.time+ "秒";
			if (data.time < 0.5){
				tfRes.text = "很好";
				color=0x579e34;
				shape.graphics.beginFill(color);
				shape.graphics.drawRect(0,0,32,6);
			}else if(data.time<=2){
				tfRes.text = "一般";
				color=0xf6ba18;
				shape.graphics.beginFill(color);
				shape.graphics.drawRect(0,0,53,6);
			}else if(data.time<10){
				tfRes.text = "较慢";
				color=0xef7431;
				shape.graphics.beginFill(color);
				shape.graphics.drawRect(0,0,74,6);
			}else{
				tfRes.text = "无法连接";
				color=0xff0000;
			}
			tfTime.color=tfRes.color=color;
		}
		/**获取一个JS变量值*/
		private function runJs(param:String) : Object{
            if (!ExternalInterface.available) return null;
            return ExternalInterface.call("function(){ return " + param + "}");
        }
		private function onClick(evt:MouseEvent):void{
			var name:String=evt.target.name;
			if(name!="btBack") return;
			if(this.index>=this.urls.length){
				WebSpeed.instance.start();
			}else{
				WebAlert.instance.start("您确定要结束测试？",new Handler(WebSpeed.instance.start));
				
			}
		}
		private function onRemovedFromStage(evt:Event):void{
			this.removeEventListener(MouseEvent.CLICK,this.onClick);
		}
		
		private function returnJS():XML{
            var xml:XML;
			var child:XML=<root>
							<info type="19001">
								<server>{urlInfo}</server>
							</info>
						</root>
            var i:int=0;
            while (i < this.urls.length){
                var data:Object=this.urls[i];
                xml=<net>
						<addr>{data.url}</addr>
						<delay>{data.time+"ms"}</delay>
					</net>
                child.info.appendChild(xml);
                i++;
            }
            return child;
        }
		private function onTextLink(evt:TextEvent):void{
			var link:String=evt.text;
			if(link!="down") return;
			navigateToURL(new URLRequest(this.bandInfo["server"]["exe"]), "_blank");

		}
	}
}